package com.bjc.base.annotation.config;

import java.lang.reflect.Method;
import java.util.Map;

import com.bjc.base.core.annotation.Permission;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.util.ReflectionUtils;

import com.bjc.base.core.annotation.PermissionPath;
import com.bjc.base.utils.AopTargetUtils;
import com.bjc.core.bean.request.PermissionReqVO;
import com.bjc.core.service.IPermissionService;

/**
 * 权限注解扫描
 * @author 许自辉
 * @date 2017年8月4日
 */
//@Component
public class PermissionScan implements ApplicationListener<ContextRefreshedEvent> {
	
	@Autowired
	private IPermissionService iPermissionService;

	@Override
	public void onApplicationEvent(ContextRefreshedEvent event) {
		// 获取RestController 注解所有的类
		Map<String, Object> map = event.getApplicationContext().getBeansWithAnnotation(PermissionPath.class);
		map.forEach((k, v) -> {
			PermissionReqVO permissionReqVO = new PermissionReqVO();
			// 获取该类的注解
			PermissionPath pp = AnnotationUtils.findAnnotation(AopTargetUtils.getTarget(v).getClass(),
					PermissionPath.class);
			permissionReqVO.setPath(pp.value());
			Method[] methods = ReflectionUtils.getAllDeclaredMethods(AopTargetUtils.getTarget(v).getClass());
			if (methods != null) {
				for (Method method : methods) {
					// 如果该方法包含RequiresPermissions注解，则取出注解的value
					if (method.isAnnotationPresent(Permission.class)) {
						Permission rp = AnnotationUtils.findAnnotation(method, Permission.class);
						if(rp.value().length == 1){
							permissionReqVO.setCode(rp.value()[0]);
							// 将扫描到的注解添加到数据库
							iPermissionService.initPermission(permissionReqVO);
						}
					}
				}
			}
		});
	}

}
